$().ready(function() {
	validateRule();
});

$.validator.setDefaults({
	submitHandler : function() {
		update();
	}
});


var officeId = $("#id").val()
debugger
var path = "http://www.fangbanban.com/images/"
$.ajax({
    url: '/xzl/housesInfo/imagesByofficeId?officeId='+officeId,
    type: 'get',
    success: function (data) {
       $list = $('.file-list')
       for(var i=0;i<data.length;i++){
       		$list.append('<li id = "img" style="border:solid red px; margin:5px 5px;" class="file-item"><img  src="'+path+data[i].physicalFileName+'" alt="" height="150"><span id = "'+data[i].id+'" class="file-del">删除</span></li>').children(':last').hide().fadeIn(100);	
       }
       $('.file-list').fadeIn(100);
    }
})


var delImagesIds = [];
//点击删除按钮事件：
$(".file-list").on('click', '.file-del', function () {
	var id = $(this).attr("id")
	
	let $parent = $(this).parent()
	
	let index = $parent.index();
	
	fileList.splice(index, 1);
	$parent.fadeOut(100, function () {
		$parent.remove()
	});
	delImagesIds.push(id);
});


var $button = $('#upload'),
//选择文件按钮
$file = $("#files"),
//回显的列表
$list = $('.file-list'),
//选择要上传的所有文件
fileList = [];
//当前选择上传的文件
var curFile;
//选择按钮change事件，实例化fileReader,调它的readAsDataURL并把原生File对象传给它，
//监听它的onload事件，load完读取的结果就在它的result属性里了。它是一个base64格式的，可直接赋值给一个img的src.
$file.on('change', function (e) {
//上传过图片后再次上传时限值数量
var numold = $('li').length;
if(numold >= 5){
layer.alert('最多上传5张图片');
return;
}
//限制单次批量上传的数量
var num = e.target.files.length;
var numall = numold + num;
if(num >5 ){
layer.alert('最多上传5张图片');
return;
}else if(numall > 5){
layer.alert('最多上传5张图片');
return;
}
//原生的文件对象，相当于$file.get(0).files;//files[0]为第一张图片的信息;
curFile = this.files;
//curFile = $file.get(0).files;
//console.log(curFile);
//将FileList对象变成数组
fileList = fileList.concat(Array.from(curFile));
//console.log(fileList);
for (var i = 0, len = curFile.length; i < len; i++) {
reviewFile(curFile[i])
}
$('.file-list').fadeIn(100);
})


function reviewFile(file) {
//实例化fileReader,
var fd = new FileReader();
//获取当前选择文件的类型
var fileType = file.type;
//调它的readAsDataURL并把原生File对象传给它，
fd.readAsDataURL(file);//base64
//监听它的onload事件，load完读取的结果就在它的result属性里了
	fd.onload = function () {
		if (/^image\/[jpeg|png|jpg|gif]/.test(fileType)) {
			$list.append('<li id = "img" style="border:solid red px; margin:5px 5px;" class="file-item"><img src="' + this.result + '" alt="" height="150"><span class="file-del">删除</span></li>').children(':last').hide().fadeIn(100);
		} else {
    $list.append('<li class="file-item"><span class="file-name">' + file.name + '</span><span class="file-del">删除</span></li>')
		}
	}
}


var delImagesIds = [];
//点击删除按钮事件：
$(".file-list").on('click', '.file-del', function () {
	var id = $(this).attr("id")
	
	let $parent = $(this).parent()
	
	let index = $parent.index();
	
	fileList.splice(index, 1);
	$parent.fadeOut(100, function () {
		$parent.remove()
	});
	
	delImagesIds.push(id);
});


//点击上传按钮事件：
$button.on('click', function () {
var name = $('#name').val();

if (name == '') {
layer.alert('请输入商品名称');
return;
}

if(fileList.length > 5){
    layer.alert('最多允许上传5张图片');
    return;
} else {
var formData = new FormData();
for (var i = 0, len = fileList.length; i < len; i++) {
    //console.log(fileList[i]);
    formData.append('upfile[]', fileList[i]);
}
formData.append('name', name);
$.ajax({
    url: './product_add.php',
    type: 'post',
    data: formData,
    dataType: 'json',
    processData: false,
    contentType: false,
    success: function (data) {
        if (data.status == '1') {
            layer.msg(data.content, {icon: 6});
        } else if (data.status == '2') {
            layer.msg(data.content, {icon: 1});
        }
    }
})
}
})

function update() {
	
	
	  var formData = new FormData();
      for (var i = 0, len = fileList.length; i < len; i++) {
         //console.log(fileList[i]);
         formData.append('files', fileList[i]);
      }
	  
      var secondhandGoodsType=$("#secondhandGoodsType").find("option:selected").val();
	  formData.append('secondhandGoodsType', secondhandGoodsType);
	  
	  var secondhandGoodsRanking=$("#secondhandGoodsRanking").find("option:selected").val();
	  formData.append('secondhandGoodsRanking', secondhandGoodsRanking);
	  
	  var secondhandGoodsDegree=$("#secondhandGoodsDegree").find("option:selected").val();
	  formData.append('secondhandGoodsDegree', secondhandGoodsDegree);
	  
	  var secondhandGoodsArea=$("#secondhandGoodsArea").find("option:selected").val();
	  formData.append('secondhandGoodsArea', secondhandGoodsArea);
	  
	 
	  var secondhandGoodsName=$("#secondhandGoodsName").val();
	  formData.append('secondhandGoodsName', secondhandGoodsName);
	  
	  var secondhandGoodsInfo=$("#secondhandGoodsInfo").val();
	  formData.append('secondhandGoodsInfo', secondhandGoodsInfo);
	  
	  var secondhandGoodsInfoDeil=$("#secondhandGoodsInfoDeil").val();
	  formData.append('secondhandGoodsInfoDeil', secondhandGoodsInfoDeil);
	  
	  
	  var secondhandGoodsCount=$("#secondhandGoodsCount").val();
	  formData.append('secondhandGoodsCount', secondhandGoodsCount);
	  
	  var secondhandGoodsAtm=$("#secondhandGoodsAtm").val();
	  formData.append('secondhandGoodsAtm', secondhandGoodsAtm);
	  	  
	  var secondhandGoodsTel=$("#secondhandGoodsTel").val();
	  formData.append('secondhandGoodsTel', secondhandGoodsTel);
	  
	  var secondhandGoodsTelname=$("#secondhandGoodsTelname").val();
	  formData.append('secondhandGoodsTelname', secondhandGoodsTelname);
	  
	  
	  var updateBy=$("#updateBy").val();
	  formData.append('updateBy', updateBy);
	  
	  var id =$("#id").val();
	  formData.append('id', id);
	  
	  
	  if(delImagesIds.length>0){
		  formData.append('delImagesIds', delImagesIds);
	  }
	  
	  
	  $.ajax({
	        url: '/xzl/secondhandGoods/update',
	        type: 'post',
	        data: formData,
	        processData: false,
	        contentType: false,
	        success: function (data) {
	        	layer.msg("操作成功");
	        	document.getElementById("signupForm").reset();
	        	$("li").remove();
	        	parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);
				fileList = []
				delImagesIds = []
	        }
	    })
}



//手机号码验证身份证正则合并：(^\d{15}$)|(^\d{17}([0-9]|X)$)
jQuery.validator.addMethod("isPhone",function(value,element){
	var length = value.length;
	var phone=/^1[3|4|5|7|8][0-9]\d{8}$/;
	return this.optional(element)||(length == 11 && phone.test(value));
},"请填写正确的11位手机号");


function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			secondhandGoodsType : {
				required : true,
				maxlength:10
			},secondhandGoodsName : {
				required : true,
				maxlength:64
			},secondhandGoodsInfo : {
				required : true,
				maxlength: 100
			},secondhandGoodsInfoDeil : {
				required : true,
				maxlength: 500
			},secondhandGoodsCount : {
				required : true,
				maxlength: 11,
				number: true
			},secondhandGoodsAtm : {
				required : true,
				number: true,
				maxlength: 15
			},secondhandGoodsRanking : {
				required : true,
				maxlength: 10
			},secondhandGoodsDegree : {
				required : true,
				maxlength: 10
			},secondhandGoodsArea : {
				required : true,
				maxlength: 10
			},secondhandGoodsTel : {
				required : true,
				isPhone: true
			},secondhandGoodsTelname : {
				required : true,
				maxlength: 20
			}
		},
		messages : {
			name : {
				required : icon + "请输入名字"
			}
		}
	})
}